 

import _ from 'lodash'
import { reactive, h, ref } from 'vue'
import { useI18n } from 'vue-i18n'
import { useRouter } from 'vue-router'
import ButtonLink from '@/components/button-link'
import { RowKey } from 'naive-ui/lib/data-table/src/interface'
import { NEllipsis,NTooltip,NIcon,NButton } from 'naive-ui'
import { EditOutlined } from '@vicons/antd'

import {
  findMasters,
  deleteMasterNode,
} from '@/service/modules/projects'
import TableAction from './components/table-action'
import {
  COLUMN_WIDTH_CONFIG,
  calculateTableWidth,
  DefaultTableWidth
} from '@/common/column-width-config'
import type { Router } from 'vue-router'
import type { IWorkflowInstance } from '@/service/modules/process-instances/types'


export function useTable() {
  const { t } = useI18n()
  const router: Router = useRouter()

  const variables = reactive({
    isShowName: ref(false),
    isShowDec: ref(false),
    columns: [],
    tableWidth: DefaultTableWidth,
    checkedRowKeys: [] as Array<RowKey>,
    tableData: [] as Array<IWorkflowInstance>,
    page: ref(1),
    limit: ref(10),
    totalPage: ref(1),
    searchVal: ref(),
    host: ref(),
    state: ref(),
    loadingRef: ref(false),
    curMasterId: ref(0),
    curNodeName: ref(''),
    curDec: ref()
  })

  const createColumns = (variables: any) => {
    variables.columns = [
      {
        title: '#',
        key: 'id',
        ...COLUMN_WIDTH_CONFIG['index'],
        render: (rowData: any, rowIndex: number) => rowIndex + 1
      },
      {
        title: t('project.master.nodeName'),
        key: 'name',
        ...COLUMN_WIDTH_CONFIG['name'],
        render: (rowData: any, unused: number) =>
        h('div', null, [
          h('span', {}, rowData.name),
          h(
            NTooltip,
            { trigger: 'hover' },
            {
              trigger: () =>
                h(
                  NButton,
                  {
                    circle: true,
                    type: 'info',
                    size: 'tiny',
                    style: { marginLeft: '5px' },
                    onClick: () => {
                      variables.curMasterId = rowData.id
                      variables.curNodeName = rowData.name || ''
                      variables.isShowName = true
                    }
                  },
                  () => h(NIcon, null, () => h(EditOutlined))
                ),
              default: () => t('project.modProjectDesc')
            }
          )
        ])
      },
      // {
      //   title: t('project.master.nodeName'),
      //   key: 'name',
      //   ...COLUMN_WIDTH_CONFIG['linkName'],
      //   className: 'workflow-name',
      //   render: (row: IWorkflowInstance) =>
      //     h(
      //       ButtonLink,
      //       {
      //         onClick: () =>
      //           void router.push({
      //             name: 'workflow-instance-detail',
      //             params: { id: row.id },
      //             query: { code: row.processDefinitionCode }
      //           })
      //       },
      //       {
      //         default: () =>
      //           h(
      //             NEllipsis,
      //             COLUMN_WIDTH_CONFIG['linkEllipsis'],
      //             () => row.name
      //           )
      //       }
      //     )
      // },
      {
        title: t('project.master.description'),
        key: 'description',
        ...COLUMN_WIDTH_CONFIG['name'],
        render: (rowData: any, unused: number) =>
        h('div', null, [
          h('span', {}, rowData.description),
          h(
            NTooltip,
            { trigger: 'hover' },
            {
              trigger: () =>
                h(
                  NButton,
                  {
                    circle: true,
                    type: 'info',
                    size: 'tiny',
                    style: { marginLeft: '5px' },
                    onClick: () => {
                      variables.curMasterId = rowData.id
                      variables.curDec = rowData.description
                      variables.isShowDec = true
                    }
                  },
                  () => h(NIcon, null, () => h(EditOutlined))
                ),
              default: () => t('project.modProjectDesc')
            }
          )
        ])
      },
      {
        title: t('project.master.host'),
        key: 'host',
        ...COLUMN_WIDTH_CONFIG['name']
      },
      {
        title: t('project.master.status'),
        key: 'state',
        ...COLUMN_WIDTH_CONFIG['state'],
        className: 'workflow-status',
        render: (_row: IWorkflowInstance) => {
          return _row.state === 0 ? '离线' : '在线'
        }
      },
      {
        title: t('project.master.cpu'),
        key: 'cpu',
        ...COLUMN_WIDTH_CONFIG['times'],
      },
      {
        title: t('project.master.ram'),
        key: 'runTimes',
        ...COLUMN_WIDTH_CONFIG['times'],
      },
      {
        title: t('project.master.operation'),
        key: 'operation',
        ...COLUMN_WIDTH_CONFIG['operation'](1),
        render: (_row: IWorkflowInstance, index: number) =>
          h(TableAction, {
            row: _row,
            onDeleteInstance: () => deleteInstance(_row.id)
          })
      }
    ]
    if (variables.tableWidth) {
      variables.tableWidth = calculateTableWidth(variables.columns)
    }
  }

  const getTableData = () => {
    if (variables.loadingRef) return
    variables.loadingRef = true
    const params = {
      page: variables.page,
      limit: variables.limit,
      name: variables.searchVal,
      host: variables.host,
      state: variables.state,
    }
    findMasters({ ...params }).then(
      (res: any) => {
        variables.totalPage = Math.ceil(res.count / params.limit) 
        variables.tableData = res && res.data.map((item: any) => {
          return { ...item }
        })
        variables.loadingRef = false
      }
    )
  }

  const deleteInstance = (id: number) => {
    deleteMasterNode({masterId:id}).then(() => {
      window.$message.success(t('project.master.success'))
      if (variables.tableData.length === 1 && variables.page > 1) {
        variables.page -= 1
      }
      getTableData()
    })
  }

  return {
    variables,
    createColumns,
    getTableData,
  }
}
